package com.lcz.authority.admin.controller.system;

import com.lcz.authority.admin.service.SysDeptService;
import com.lcz.authority.admin.service.SysPostService;
import com.lcz.authority.admin.service.SysRoleService;
import com.lcz.authority.admin.service.SysUserService;
import com.lcz.authority.admin.web.service.SysPermissionService;
import com.lcz.authority.common.annotation.ApiResource;
import com.lcz.authority.common.core.page.PageResult;
import com.lcz.authority.common.domain.AjaxResult;
import com.lcz.authority.common.domain.R;
import com.lcz.authority.common.domain.entity.SysDeptEntity;
import com.lcz.authority.common.domain.entity.SysPostEntity;
import com.lcz.authority.common.domain.entity.SysRoleEntity;
import com.lcz.authority.common.domain.entity.SysUserEntity;
import com.lcz.authority.common.enums.AppCodeEnum;
import com.lcz.authority.common.enums.ResBizTypeEnum;
import com.lcz.authority.common.utils.SecurityUtils;
import com.lcz.authority.common.utils.StringUtils;
import com.lcz.authority.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lcz
 * @desc 用户管理
 * @mail lcz_0130@163.com
 * @date 2024/05/06
 */
@RestController
@RequestMapping("/system/user")
@ApiResource(name = "用户管理", resBizType = ResBizTypeEnum.SYSTEM, appCode = AppCodeEnum.SYSTEMMODULES)
@Api(tags = "用户管理")
public class SysUserController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysPostService postService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private SysPermissionService permissionService;

    @GetMapping(value = "list", name = "用户管理-分页")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @ApiOperation("分页用户列表")
    public R page(SysUserEntity sysUserEntity) {
        PageResult<SysUserEntity> page = userService.page(sysUserEntity);
        return R.ok().put(page);
    }

    @GetMapping(value = {"{userId}", "/"}, name = "用户管理-获取用户信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @ApiOperation("获取用户信息")
    public R getInfo(@PathVariable(value = "userId", required = false) String userId) {
        R res = R.ok();
        List<SysRoleEntity> roles = roleService.selectRoleAll();
        res.put("roles", SysUserEntity.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        res.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUserEntity sysUserEntity = userService.selectUserById(userId);
            res.put("data", sysUserEntity);
            res.put("roleIds", sysUserEntity.getRoles().stream().map(SysRoleEntity::getRoleId).collect(Collectors.toList()));
            res.put("postIds", sysUserEntity.getPosts().stream().map(SysPostEntity::getPostId).collect(Collectors.toList()));
        }
        return res;
    }

    @PostMapping(name = "用户管理-新增")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @ApiOperation("新增用户")
    public R add(@Validated @RequestBody SysUserEntity sysUserEntity) {
        userService.insertUser(sysUserEntity);
        return R.ok();
    }

    @PutMapping(name = "用户管理-修改")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @ApiOperation("修改用户")
    public R update(@Validated @RequestBody SysUserEntity user) {
        userService.checkUserAllowed(user);
        if (!(userService.checkUserNameUnique(user))) {
            return R.error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhoneNumber())
                && !(userService.checkPhoneUnique(user))) {
            return R.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && !(userService.checkEmailUnique(user))) {
            return R.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(null);
        return R.ok(userService.updateUser(user));
    }

    @DeleteMapping(value = "/{userIds}", name = "用户管理-删除")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @ApiOperation("删除用户")
    public R remove(@PathVariable String[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return R.error("当前用户不能删除");
        }
        return R.ok(userService.deleteUserByIds(userIds));
    }

    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/authRole/{userId}", name = "用户管理-根据用户编号获取授权角色")
    @ApiOperation("根据用户编号获取授权角色")
    public R authRole(@PathVariable("userId") String userId) {
        R res = R.ok();
        SysUserEntity user = userService.selectUserById(userId);
        List<SysRoleEntity> roles = roleService.selectRolesByUserId(userId);
        res.put("user", user);
        res.put("roles", SysUserEntity.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return res;
    }

    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping(value = "/authRole", name = "用户管理-用户授权角色")
    @ApiOperation("用户授权角色")
    public R insertAuthRole(String userId, String[] roleIds) {
        if (!SysUserEntity.isAdmin(userId)) {
            userService.insertUserAuth(userId, roleIds);
            return R.ok();
        } else {
            return R.error("不可操作超级管理员");
        }
    }

    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @PutMapping(value = "/resetPwd", name = "用户管理-重置密码")
    @ApiOperation("重置密码")
    public R resetPwd(@RequestBody SysUserEntity user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return R.ok(userService.resetPwd(user));
    }

    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping(value = "/changeStatus", name = "用户管理-修改状态")
    @ApiOperation("修改状态")
    public R changeStatus(@RequestBody SysUserEntity user) {
        userService.checkUserAllowed(user);
        userService.updateUserStatus(user);
        return R.ok();
    }

    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping(value = "/export", name = "用户管理-导出")
    @ApiOperation("导出用户数据")
    public void export(HttpServletResponse response, SysUserEntity user) {
        List<SysUserEntity> list = userService.page(user).getRows();
        ExcelUtil<SysUserEntity> util = new ExcelUtil<>(SysUserEntity.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDeptEntity dept) {
        return AjaxResult.success(deptService.selectDeptTreeList(dept));
    }

}
